//
//  CZAccountViewModel.swift
//  GZWeiboMing
//
//  Created by 1 on 16/4/1.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit

class CZAccountViewModel: NSObject {
    //单例
    static let sharedInstance: CZAccountViewModel = CZAccountViewModel()
    
    private override init() {
        super.init()
        
        //从沙盒里面加载账号
        userAccount = loadUserAccount()
    }
    //账号的路径
    private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/account.plist")
    
    //账号
    var userAccount: CZUserAccount?
    
    //加载 access_token, post
    //1、定义闭包 
    func loadAccessToken(code: String, completion: (error: NSError?) -> ()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //拼接参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "auyhorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        //发送请求
        CZNetworkTool.sharedInstance.afnManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print("result: \(result)")
            //将accessToken保存起来
            if let dict = result as? [String: AnyObject] {
                self.userAccount = CZUserAccount(dict: dict)
                print("userAccount: \(self.userAccount)")
                //保存模型到沙盒
                self.saveUserAccount()
                //通知控制器保存完成
                completion(error: nil)
            
            }
            }) { (_, error) -> Void in
                completion(error: error)
        }
    }
    //保存模型到沙盒
    private func saveUserAccount() {
        if userAccount != nil {
            print("accountPath: \(accountPath)")
            
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath!)
        }
    }
    //从沙盒中加载数据
    private func loadUserAccount() -> CZUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath!) as? CZUserAccount
        
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("userAccount: \(userAccount)")
            return userAccount
        }
       return nil
    }

}
